# MEM_SIZE=4G
MEM_SIZE ?= 8G
CHOST ?= aarch64-mix210-linux
UBOOT_ARCH ?= arm
REG_INFO ?= reg_info_$(MEM_SIZE).bin
DEFCONFIG ?= ss928v100_emmc_defconfig
UBOOT_ENV ?= uEnv_$(MEM_SIZE).txt
OUTPUT_DIR ?= $(CURDIR)/output

UBOOT_DIR=$(CURDIR)/u-boot-2020.01
CROSS_COMPILE = $(CHOST)-
CC=$(CROSS_COMPILE)gcc

PHONY+=all
all:boot_image boot_env boot_env_tools

PHONY+=boot_env
boot_env:boot_image
	mkdir -p $(OUTPUT_DIR)
	$(CC) -x assembler-with-cpp -E -P -o uEnv/.uEnv.tmp uEnv/$(UBOOT_ENV)
	if [ ! -e $(UBOOT_DIR)/tools/mkenvimage ];then make uboot;fi
	$(UBOOT_DIR)/tools/mkenvimage -s 0x100000 -o $(OUTPUT_DIR)/boot_env_$(MEM_SIZE).bin uEnv/.uEnv.tmp
	rm uEnv/.uEnv.tmp

PHONY+=boot_env_tools
boot_env_tools:boot_image
	cd $(UBOOT_DIR);\
	make ARCH=$(UBOOT_ARCH) CROSS_COMPILE=$(CROSS_COMPILE) envtools
	cp $(UBOOT_DIR)/tools/env/fw_printenv $(OUTPUT_DIR)/
	cp $(UBOOT_DIR)/tools/env/fw_env.config $(OUTPUT_DIR)/
	
PHONY+=boot_image
boot_image:uboot
	mkdir -p $(OUTPUT_DIR)
	cd boot/gsl;\
	make CHIP=ss928v100 CROSS_COMPILE=$(CROSS_COMPILE);\
	cd ../image_map;\
	cp ../gsl/pub/gsl.bin ./;\
	cp $(UBOOT_DIR)/u-boot-ss928v100.bin u-boot-original.bin;\
	cp $(CURDIR)/reg_info/$(REG_INFO) .reg;\
	python3 oem/oem_quick_build.py;\
	cp image/oem/boot_image.bin $(OUTPUT_DIR)/boot_image_$(MEM_SIZE).bin

PHONY+=uboot
uboot:$(UBOOT_DIR)/.config
	cp $(CURDIR)/reg_info/$(REG_INFO) $(UBOOT_DIR)/.reg;\
	cd $(UBOOT_DIR);\
	make ARCH=$(UBOOT_ARCH) CROSS_COMPILE=$(CROSS_COMPILE) -j 20;\
	make ARCH=$(UBOOT_ARCH) CROSS_COMPILE=$(CROSS_COMPILE) u-boot-z.bin

$(UBOOT_DIR)/.config:$(UBOOT_DIR)/configs/$(DEFCONFIG)
	cd $(UBOOT_DIR);\
	make ARCH=$(UBOOT_ARCH) CROSS_COMPILE=$(CROSS_COMPILE) $(DEFCONFIG)

PHONY+=ubootcfg
ubootcfg:$(UBOOT_DIR)/.config
	cd $(UBOOT_DIR);\
	make ARCH=$(UBOOT_ARCH) CROSS_COMPILE=$(CROSS_COMPILE) menuconfig;\
	cp .config $(UBOOT_DIR)/configs/$(DEFCONFIG)

PHONY+=clean
clean:
	cd $(UBOOT_DIR);\
	make ARCH=$(UBOOT_ARCH) clean
	cd boot/gsl;make CHIP=ss928v100 clean; 
	rm -rf $(OUTPUT_DIR)

PHONY+=help
help:
	@echo "uboot                编译生成u-boot-ss928v100.bin"
	@echo "boot_image           最终烧录的镜像"
	@echo "ubootcfg             配置uboot,配置后自动保存到(DEFCONFIG=$(DEFCONFIG))"
	@echo "clean                清除构建生成的文件"
	@echo "boot_env             环境变量分区镜像,依赖于(UBOOT_ENV=$(UBOOT_ENV))"
	@echo "boot_env_tools       Linux中操作u-boot环境变量分区的工具"

.PHONY:$(PHONY)
